//
//  KPDViewController.m
//  SelfDriving
//
//  Created by apple on 16/7/25.
//  Copyright © 2016年 apple. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
#import <AVPlayerCacheLibrary/AVPlayerCacheLibrary-umbrella.h>
#import "SRVideoPlayer.h"
#import "TBPlayer.h"
#import "KPDViewController.h"
#import "DMHeartFlyView.h"
#import "FullScreenViewController.h"
#import "KPCell.h"
#import "BusinessService+FJ.h"
#import "BusinessService+User.h"
#import "TalkingRecordView.h"
#import "AudioMsgPlayer.h"
#import "ReportViewController.h"
#import "UIImage+wiRoundedRectImage.h"
#import "FriendDetailsMainVC.h"
#define MINDISTANCE (5.0f)   //滑动最小距离，用于下面计算距离使用
//快拍详细
@interface KPDViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,UIAlertViewDelegate,UIActionSheetDelegate,UIAccelerometerDelegate,UIAlertViewDeleagte,PlayerDelegate,NSURLConnectionDelegate,NSURLConnectionDataDelegate>
@property (weak, nonatomic) IBOutlet UIView *titleview;
@property (weak, nonatomic) IBOutlet UITableView *table;  //显示消息列表的table
@property (weak, nonatomic) IBOutlet UILabel *qmtishiLble;
@property (weak, nonatomic) IBOutlet UIButton *yybtn;
@property (weak, nonatomic) IBOutlet UIButton *btn1;
@property (weak, nonatomic) IBOutlet UIButton *bnt2;
@property (weak, nonatomic) IBOutlet UIButton *btn3;
@property (weak, nonatomic) IBOutlet UIButton *btn4;
@property (weak, nonatomic) IBOutlet UIButton *btn5;
@property (strong, nonatomic) UIButton *bqBtn;
@property (strong, nonatomic) UIButton *senderBtn;
@property (strong, nonatomic) UITextView *hfText;  //文本输入框
@property (strong, nonatomic) UIButton *soundsBtn;//长按发言按钮
@property (weak, nonatomic) IBOutlet UIView *bgview;
@property (weak, nonatomic) IBOutlet UIButton *mic_btn;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property (weak, nonatomic) IBOutlet UIImageView *bgimg;

@property (weak, nonatomic) IBOutlet UILabel *msgLogin;

@property (strong, nonatomic) UIView *inputView;

@property (nonatomic) CGPoint g_gestureStartPoint;//第二种方式中使用到得记录全局的起始手势位置
@property (nonatomic,strong)NSTimer *countTimer;
@property (nonatomic,assign)int secondsCountDown;
//监控进度
@property (nonatomic,strong)NSTimer *avTimer;
//进度条(托控件)
@property (weak, nonatomic) IBOutlet UISlider *progress;
@property (weak, nonatomic) IBOutlet UIButton *bofangbtn;

@property (nonatomic,strong)SRVideoPlayer * srPlayer;
@property (nonatomic,strong)UIView* playerView;

@property (nonatomic, assign)int xhwZanCount;

//xhw2018-1-21加
@property (nonatomic, strong)NSMutableData *fileData;

@property (nonatomic, assign) long long totalLength;

@property (nonatomic, assign) long long currentLength;

@property (nonatomic, strong)NSFileHandle * writeHandle;;

@end
@implementation KPDViewController
{
    NSMutableArray *resultArray;  //消息体Array
    NSMutableArray *imgdata; //最新用户头像array
    UIScrollView *scview;
    NSTimer *timer;
    //点击按住说话之后弹出的正在录制的视图
    TalkingRecordView*      recordView;
    int isqiangmai;//是否是抢麦
    int istablescoolr;
    int isbofgang; //是否播放标识
    NSString *meetingNumber;// 蓉联会议ID
    
    BOOL isMute;//管理员开关麦
    NSInteger controlMicBtnStatus; //0:未控麦状态 1:控麦中 2:控麦成功
    NSInteger speakTimeInterval;
    UILabel *_lable;
    UILabel *_namelabel;
    
    UIButton *pinglunBtn;
    CameraMoveDirection direction;
    
//    TPlayerView* _player;

    AVPlayer *_player;
    AVPlayerItem *_playItem;
    AVPlayerLayer *_playerLayer;
    AVPlayerLayer *_fullPlayer;
//
    BOOL _isPlaying;
    int  volume;
    
    
    
    
    UIButton *_playBtn;
    int iscomm;//评论开关
    int getMsg;
    TCNotify *not;
    
    LoginResponseModel *user;
    LoginResponseModel *models;
    int istuichu;  //是否点击退出
    
    NSTimer *timer1;
    int ot;
    
    UIButton *xbtn;
    UIAlertViews *alert;
    int isplay;
    
    UIButton *backbtn;
    //是否是全屏模式(xhw11月15号加)
    BOOL isFullScreen;
    
}
#pragma mark -xhw视频下载
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // 文件路径
    NSString* ceches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString* filepath = [ceches stringByAppendingPathComponent:response.suggestedFilename];
    
    // 创建一个空的文件到沙盒中
    NSFileManager* mgr = [NSFileManager defaultManager];
    [mgr createFileAtPath:filepath contents:nil attributes:nil];
    
    // 创建一个用来写数据的文件句柄对象
    self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filepath];
    NSLog(@"快拍详细里面->视频缓存路径->filepath->%@",filepath);

    // 获得文件的总大小
    self.totalLength = response.expectedContentLength;
    

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [self.writeHandle seekToEndOfFile];
    
    // 将数据写入沙盒
    [self.writeHandle writeData:data];
    
    // 累计写入文件的长度
    self.currentLength += data.length;
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//    // 拼接文件路径
//    NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//    NSString *file = [cache stringByAppendingPathComponent:@"xhw下载"];
//
//    // 写到沙盒中
//    [self.fileData writeToFile:file atomically:YES];
    
    self.currentLength = 0;
    self.totalLength = 0;
    // 关闭文件
    [self.writeHandle closeFile];
    self.writeHandle = nil;
}

- (NSString *)cacheFileExistsWithURL:(NSURL *)url {
    NSString* ceches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString* filepath;
    NSArray* urlStrArr = [url.absoluteString componentsSeparatedByString:@"/"];
    if (urlStrArr.count != 0) {
        NSString * mp4Str = urlStrArr[urlStrArr.count - 1];
        filepath = [ceches stringByAppendingPathComponent:mp4Str];
    }
    else {
        filepath = [ceches stringByAppendingPathComponent:url.absoluteString];
    }
    if ([[NSFileManager defaultManager] fileExistsAtPath:filepath]) {
        return filepath;
    }
    return nil;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
    //UIStatusBarStyleDefault = 0 黑色文字，浅色背景时使用
    //UIStatusBarStyleLightContent = 1 白色文字，深色背景时使用
}
- (BOOL)prefersStatusBarHidden
{
    return YES; //返回NO表示要显示，返回YES将hiden
}
- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [_srPlayer destroyPlayer];
}

-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
    [AppDelegate shareDelegate].isScollBack = NO;
    //    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [self.avTimer invalidate];
    
    [backbtn removeFromSuperview];
    backbtn = nil;
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [AppDelegate shareDelegate].isScollBack = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    //    [IQKeyboardManager sharedManager].enable = NO;
    [self initDta];
}
-(void)initdata:(NSNotification *)sender{
    not = sender.object;
    NSMutableDictionary *dic = [JsonService jsonObjectWithString:not.content];
    [AppDelegate shareDelegate].meetingNum = [dic objectForKey:@"meetingNum"];
}
-(void)initViewWill{
    _bgview.transform = CGAffineTransformMakeTranslation(0, 0);
    _bgimg.transform = CGAffineTransformMakeTranslation(0, 0);
    self.navigationController.navigationBarHidden = YES;
    imgdata = [[NSMutableArray alloc]init];
    if([_model.uid intValue] != [[AppDelegate shareDelegate].user.uid intValue]){
        [self inserhead];
        _mic_btn.hidden = YES;
        _msgLogin.hidden = YES;
        if (_model.meetingNum.length!=0) {
            [[ECDevice sharedInstance].meetingManager joinMeeting:_model.meetingNum ByMeetingType:ECMeetingType_MultiVoice andMeetingPwd:@"yimisns" completion:^(ECError *error, NSString *meetingNumber) {
                if (error.errorCode == ECErrorType_NoError)
                {
                    NSLog(@"加入会议成功");
                    _mic_btn.hidden = NO;
                    _msgLogin.hidden = NO;
                    [[ECDevice sharedInstance].VoIPManager enableLoudsSpeaker:YES];
                    //                 [SVProgressHUD showImage:nil status:@"进入直播成功"];
                }
                else
                {
                    _mic_btn.hidden = YES;
                    _msgLogin.hidden = YES;
                    NSLog(@"加入会议失败");
                    NSString *msg = @"进入直播失败，请稍后再试！";
                    msg = error.errorDescription.length==0?msg:error.errorDescription;
                    [SVProgressHUD showErrorWithStatus:msg];
                    
                    //                [SVProgressHUD showImage:nil status:@"进入直播失败"];
                    
                }
            }];
        }
    }
}

- (void)xhwTap {
    _inputView.hidden = YES;
    [self.view endEditing:YES];
}
- (void)viewDidLoad {
    UITapGestureRecognizer *xhwTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(xhwTap)];
    [_table addGestureRecognizer:xhwTapGes];  //xhw2018-1-29加
    
    _secondsCountDown = 5;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearSession:) name:@"clearSession" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initGroupList:) name:@"groupList" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zhibokaiqi:) name:@"zhibokaiqi" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zhibojiesu:) name:@"zhibojiesu" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(iscomKuaipai:) name:@"iscomKuaipai" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zanKuaipai:) name:@"zanKuaipai" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initnuber:) name:@"initnuber" object:nil];

    [super viewDidLoad];
    [self initViewWill];
    [backbtn setImage:[UIImage qmui_imageWithShape:QMUIImageShapeNavClose size:WH(15, 15) tintColor:UIColorWhite] forState:UIControlStateNormal];
    _msgLogin.layer.cornerRadius = 10;
    _msgLogin.clipsToBounds = YES;
    self.navigationController.navigationBarHidden = YES;
    
    
    
    //添加系统的键盘弹出和收起通知的观察者
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidShow:) name:UIKeyboardDidShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardDidHide:) name:UIKeyboardDidHideNotification object:nil];
    
    //语音
    recordView = [[TalkingRecordView alloc] initWithFrame:CGRectMake(80, (self.view.height-160)/2, self.view.width-160, 160) del:self];
    [self.view addSubview:recordView];
    recordView.hidden = YES;
    
    [self initnuber:nil];
    
    _table.showsVerticalScrollIndicator = NO;
    _table.showsHorizontalScrollIndicator = NO;
    _bgimg.contentMode = UIViewContentModeScaleAspectFit;
    NSString *url;
    if (_user.video.length == 0) {
        if (![ValidateHelper isHttpHead:_user.img]) { //imgUrl是否有http前缀，如果没有就手动加http://yimisns.com
            url = [NSString stringWithFormat:@"%@%@",img_Url,_user.img];
        }else{
            url = _user.img;
        }
        CGFloat h = [ValidateHelper setimgeSize:url img:_bgimg];  //xhw注释:设置图片
        //        CGRect s = _bgimg.frame;
        //        s.size.height = h;
        //        _bgimg.frame = s;
        
        //        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCRE_WIDTH, 220)];
        //       CGFloat rh = [ValidateHelper setimgeSize:url img:img];
        //        CGRect im = img.frame;
        //        im.size.height = rh;
        //        im.origin.y = SCRE_HEIGHT/2- rh/2;
        //        img.frame = im;
        //        [self.view addSubview:img];
        
    }else if (_user.video != nil && _user.video.length != 0 ){
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished1:)name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        NSURL *url =[NSURL URLWithString:_user.video];

        if (![ValidateHelper isHttpHead:_user.video]) {
            url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",img_Url,_user.video]];
        }
        
        
        
        if (_playerLayer) {
            [_playerLayer removeFromSuperlayer];
        }
        NSLog(@"熊宏伟%@",url);
        
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        request.URL = url;
        [request setHTTPMethod:@"GET"];
        
        [NSURLConnection connectionWithRequest:request delegate:self];
        
        NSString * cacheFilePath = [self cacheFileExistsWithURL:url];
        
        if (cacheFilePath) {
            NSLog(@"有缓存过这个视频");
            NSURL *xhwurl = [NSURL fileURLWithPath:cacheFilePath];
            _playItem = [AVPlayerItem playerItemWithURL:xhwurl];
        }
        else {
            _playItem = [AVPlayerItem playerItemWithURL:url]; //加载视频 xhw2018-2-8加
        }
        
//        _playItem = [AVPlayerItem playerItemWithURL:url]; //加载视频  //xhw2018-2-8注释
        _player = [AVPlayer playerWithPlayerItem:_playItem];
        _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
        _playerLayer.frame = _bgimg.frame;
        _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;//视频填充模式
        [_bgimg.layer addSublayer:_playerLayer];

        
//        _player = [[TPlayerView alloc]initWithFrame:_bgimg.bounds videoUrl:[NSString stringWithFormat:@"%@%@",img_Url,_user.video] WithVideoName:@"temp" WithDelegate:self];
//        NSLog(@"%@", [NSString stringWithFormat:@"%@%@",img_Url,_user.video]);
//        [_bgimg addSubview:_player];
//        [_player loadVideoData];
//        _playerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _bgimg.frame.size.width/3*2, _bgimg.frame.size.height/3*2)];
//        _playerView.center = _bgimg.center;
//        [_bgimg addSubview:_playerView];
//        _srPlayer = [SRVideoPlayer playerWithVideoURL:url playerView:_playerView playerSuperView:_playerView.superview];
//        _srPlayer.playerEndAction = SRVideoPlayerEndActionLoop;
//        [_srPlayer play];
//        [[TBPlayer sharedInstance] playWithUrl:url showView:self.view];
        [_progress setThumbImage:[UIImage imageNamed:@"图标---播放进行圆"]  forState:UIControlStateNormal];
        //监控播放进度
        self.avTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timer)userInfo:nil repeats:YES];
    }
    UIPanGestureRecognizer *recognizer = [[ UIPanGestureRecognizer alloc] initWithTarget: self action: @selector (qiehuanView:)];
    //添加点击事件shou(xhw9月19号添加)
    
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.view addGestureRecognizer:tapGes];
    
    
    [self.view addGestureRecognizer:recognizer];
    [[[[UIApplication sharedApplication] windows] firstObject] addGestureRecognizer:recognizer];
//    [self initDta];  //布局返回等按钮，以及获取聊天列表刷新table
    
    iscomm = [_model.cancomment intValue];
    getMsg = [_model.cancomment intValue];
    int x;
    if([_user.width intValue] > [_user.height intValue]){
        [AppDelegate shareDelegate].shouldChangeOrientation = YES;
        self.view.bounds = CGRectMake(0, 0, [AppDelegate shareDelegate].sheigt, [AppDelegate shareDelegate].swhidth);
        
        
        
//        if (_user.video.length == 0) {
            _bgimg.frame = self.view.bounds;
//        }else if (_user.video != nil && _user.video.length != 0 ){
//            _playerLayer.frame = self.view.bounds;
//        _playerView.frame = self.view.bounds;
//        }
//        NSLog(@"hhhhhh ww:%f---hh:%f",self.view.bounds.size.width,self.view.bounds.size.height);
        x = [AppDelegate shareDelegate].sheigt;
        
        
        if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
            SEL selector = NSSelectorFromString(@"setOrientation:");
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
            [invocation setSelector:selector];
            [invocation setTarget:[UIDevice currentDevice]];
            int val = UIInterfaceOrientationLandscapeLeft;
            [invocation setArgument:&val atIndex:2];
            [invocation invoke];
        }
    }else{
        self.view.bounds = CGRectMake(0, 0, [AppDelegate shareDelegate].swhidth, [AppDelegate shareDelegate].sheigt);
//        if (_user.video.length == 0) {
            _bgimg.frame = self.view.bounds;
//        }else if (_user.video != nil && _user.video.length != 0 ){
//            _playerLayer.frame = self.view.bounds;
//        _playerView.frame = self.view.bounds;
//        }
//        NSLog(@"wwwwww ww:%f---hh:%f",self.view.bounds.size.width,self.view.bounds.size.height);

        if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
            SEL selector = NSSelectorFromString(@"setOrientation:");
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
            [invocation setSelector:selector];
            [invocation setTarget:[UIDevice currentDevice]];
            int val = UIInterfaceOrientationPortrait;
            [invocation setArgument:&val atIndex:2];
            [invocation invoke];
        }
        
        x = [AppDelegate shareDelegate].swhidth;
    }
    
    //聊天控件
    _inputView = [[UIView alloc]initWithFrame:CGRectMake(0, [_user.width intValue] > [_user.height intValue]?x - 150:SCRE_HEIGHT, x, 50)];

    _inputView.backgroundColor = UIColorFromRGB(0xf3f3f3);
    _bqBtn = [[UIButton alloc]initWithFrame:CGRectMake(12, 12, 30, 26)];
    [_bqBtn setImage:[UIImage imageNamed:@"ltyy"] forState:UIControlStateNormal];
    [_bqBtn setImage:[UIImage imageNamed:@"图标---键盘"] forState:UIControlStateSelected];
    
    _bqBtn.tag = 726;
    [_bqBtn addTarget:self action:@selector(soundBtnChange:) forControlEvents:UIControlEventTouchUpInside];
    //xhw9月18改：语音改为像单聊中一样的
//    [_bqBtn addTarget:self action:@selector(btnTalkTouchBegin:) forControlEvents:UIControlEventTouchDown];
//    [_bqBtn addTarget:self action:@selector(btnTalkTouchCancel:) forControlEvents:UIControlEventTouchUpOutside];
//    [_bqBtn addTarget:self action:@selector(end:) forControlEvents:UIControlEventTouchUpInside];
//    [_bqBtn addTarget:self action:@selector(btnTalkDragInside:) forControlEvents:UIControlEventTouchDragInside];
//    [_bqBtn addTarget:self action:@selector(btnTalkDragOutside:) forControlEvents:UIControlEventTouchDragOutside];
    
    
    
    
    [_inputView addSubview:_bqBtn];
    //    _inputView.layer.cornerRadius = 4;
    _hfText = [[UITextView alloc]initWithFrame:CGRectMake(50, 8, x-(60+45), 30)];
    _hfText.layer.cornerRadius = 5;
    _hfText.delegate = self;
    [_inputView addSubview:_hfText];
    
    //xhw9月18改:
    _soundsBtn = [[UIButton alloc]initWithFrame:_hfText.frame];
    _soundsBtn.layer.cornerRadius = 5;
    _soundsBtn.layer.borderColor = colorBG.CGColor;
    //    _sender_btn.layer.borderColor = UIColorRed.CGColor;
    _soundsBtn.layer.borderWidth = 0.5;
    
    _soundsBtn.backgroundColor = [UIColor clearColor];
    [_soundsBtn setTitle:@"长按发言" forState:UIControlStateNormal];
    [_soundsBtn setBackgroundColor:colorBG forState:UIControlStateNormal];
    [_soundsBtn addTarget:self action:@selector(btnTalkTouchBegin:) forControlEvents:UIControlEventTouchDown];
    [_soundsBtn addTarget:self action:@selector(btnTalkTouchCancel:) forControlEvents:UIControlEventTouchUpOutside];
    [_soundsBtn addTarget:self action:@selector(end:) forControlEvents:UIControlEventTouchUpInside];
    [_soundsBtn addTarget:self action:@selector(btnTalkDragInside:) forControlEvents:UIControlEventTouchDragInside];
    [_soundsBtn addTarget:self action:@selector(btnTalkDragOutside:) forControlEvents:UIControlEventTouchDragOutside];
    //xhw2018-3-15加
//    UILongPressGestureRecognizer * soundLongGes = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pressGesture:)];
//    soundLongGes.minimumPressDuration = 0.5;
//    [_soundsBtn addGestureRecognizer:soundLongGes];
    
    [_soundsBtn setTitleColor:UIColorBlack forState:UIControlStateNormal];
    //    _sender_btn.highlighted = YES;
    _soundsBtn.hidden = YES;
    [_inputView addSubview:_soundsBtn];

    
    
    
    _senderBtn = [[UIButton alloc]initWithFrame:CGRectMake(x-50, 8, 45, 30)];
    _senderBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_senderBtn setTitle:@"发送" forState:UIControlStateNormal];
    [_senderBtn setBackgroundColor:UIColorFromRGB(0x84FF8C)];
    [_senderBtn addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
    [_inputView addSubview:_senderBtn];
    [_senderBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _senderBtn.layer.cornerRadius = 4;
    _inputView.hidden = YES;
    [self.view addSubview:_inputView];
    
    
    
    
    UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
    // 2.设置代理
    accelerometer.delegate = self;
    
    // 3.设置采样间隔
    accelerometer.updateInterval = 0.3;
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDeviceOrientationChange) name:UIDeviceOrientationDidChangeNotification object:nil];
    

}

//-(UIInterfaceOrientationMask)supportedInterfaceOrientations
//{
//    return UIInterfaceOrientationMaskLandscape;
//}
//-(BOOL)shouldAutorotate
//{
//    return YES;
//}

//点击语音或者是键盘按钮切换
- (void)soundBtnChange:(UIButton*)sender {
    sender.selected = !sender.selected;
    _soundsBtn.hidden = !_soundsBtn.hidden;
    _hfText.hidden = !_hfText.hidden;
    _senderBtn.hidden = !_senderBtn.hidden; //xhw2018-3-19加
}

//开始
- (IBAction)play:(id)sender {
    UIButton *btn = (UIButton *)sender;
    btn.selected = !btn.selected;
    if (isplay==0) {
        [_player play];

        isplay = 1;
    }else{
        isplay = 0;
        [_player pause];

    }
}



#pragma mark -监控播放进度方法
//在viewDidLoad中加入定时器执行该方法

- (void)timer
{
    self.progress.value = CMTimeGetSeconds(_player.currentItem.currentTime) / CMTimeGetSeconds(_player.currentItem.duration);
    float total = CMTimeGetSeconds([_playItem duration]);
    float current = CMTimeGetSeconds(_player.currentItem.currentTime);
    if (!isnan(total)) {
        if(total > 10.0){ //如果视频播放时长>10进度条才显示
            _bofangbtn.hidden = NO;
            _progress.hidden = NO;
        }else{
            [_player play];
        }
    }
//    [_srPlayer play];

//    self.progress.value = [TBPlayer sharedInstance].current/[TBPlayer sharedInstance].duration;
//    if ([TBPlayer sharedInstance].duration>10.0) {
//        _bofangbtn.hidden = NO;
//        _progress.hidden = NO;
//    }
//    else {
//        [[TBPlayer sharedInstance]resume];
//    }
    
    
}
#pragma mark - 貌似没用
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    if (_inputView.hidden == NO) {
        return;
    }
    //    if (acceleration.x >= 0.75) {//home button left
    //        //旋转屏幕，但是只旋转当前的View
    //        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeLeft];
    //        self.view.transform = CGAffineTransformMakeRotation(M_PI*1.5);
    //        CGRect frame = [UIScreen mainScreen].applicationFrame;
    //        self.view.bounds = CGRectMake(0, 0, frame.size.height, SCRE_WIDTH);
    //    }
    //    else if (acceleration.x <= -0.75) {//home button right
    //        //旋转屏幕，但是只旋转当前的View
    //        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
    //        self.view.transform = CGAffineTransformMakeRotation(M_PI/2);
    //        CGRect frame = [UIScreen mainScreen].applicationFrame;
    //        self.view.bounds = CGRectMake(0, 0, frame.size.height, SCRE_WIDTH);
    //    }
    //    else if (acceleration.y <= -0.75) {
    //        //旋转屏幕，但是只旋转当前的View
    //        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortraitUpsideDown];
    //        self.view.transform = CGAffineTransformIdentity;
    //        self.view.bounds = CGRectMake(0, 0, SCRE_WIDTH, SCRE_HEIGHT);
    //    }
    //    else if (acceleration.y >= 0.75) {
    //        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationUnknown];
    //        self.view.transform = CGAffineTransformMakeRotation(-M_PI);
    //        self.view.bounds = CGRectMake(0, 0, SCRE_WIDTH, SCRE_HEIGHT);
    //    }
    //    else {
    //        // Consider same as last time
    //        return;
    //    }    if (_user.video.length == 0) {
    //        _bgimg.frame = self.view.bounds;
    //    }else if (_user.video != nil && _user.video.length != 0 ){
            _playerLayer.frame = self.view.bounds;
    //    }
}

- (IBAction)playAction:(UIButton *)sender {
    [_player play];
//    [_srPlayer play];
    sender.hidden = YES;
}
-(void)playbackFinished1:(NSNotification *)notification
{
    AVPlayerItem * p = [notification object];
    //关键代码
    [p seekToTime:kCMTimeZero];
    [_player play];
//    [_srPlayer play];
}

-(void)initDta{
    if([_model.uid intValue] == [[AppDelegate shareDelegate].user.uid intValue]){//主播
        [self initViewzijikandao];
    }else{
        [self initViewbierenkandao];
    }
    resultArray = (NSMutableArray *)[[ThinkChat instance] getMessageListTimeLineWithID:_model.id typeChat:200 sinceRowID:0 maxRowID:0 count:3 page:0];
    [[ThinkChat instance]hasReadSessionID:_model.id typeChat:200];
    [_table reloadData];
    
    
    
    
}
- ( CameraMoveDirection )determineCameraDirectionIfNeeded:( CGPoint )translation

{
    
    if (direction != kCameraMoveDirectionNone)
        
        return direction;
    
    // determine if horizontal swipe only if you meet some minimum velocity
    
    if (fabs(translation.x) > 20)
        
    {
        
        BOOL gestureHorizontal = NO;
        
        if (translation.y == 0.0 )
            
            gestureHorizontal = YES;
        
        else
            
            gestureHorizontal = (fabs(translation.x / translation.y) > 5.0 );
        
        if (gestureHorizontal)
            
        {
            
            if (translation.x > 0.0 )
                
                return kCameraMoveDirectionRight;
            
            else
                
                return kCameraMoveDirectionLeft;
            
        }
        
    }
    
    // determine if vertical swipe only if you meet some minimum velocity
    
    else if (fabs(translation.y) > 20)
        
    {
        BOOL gestureVertical = NO;
        if (translation.x == 0.0 )
            gestureVertical = YES;
        else
            gestureVertical = (fabs(translation.y / translation.x) > 5.0 );
        if (gestureVertical)
            
        {
            if (translation.y > 0.0 )
                return kCameraMoveDirectionDown;
            else
                return kCameraMoveDirectionUp;
        }
    }
    return direction;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//    if (self.secondsCountDown != 3) {
//        return;
//    }    //xhw2018-1-29加
    _inputView.hidden = YES;
    [self.view endEditing:YES];
}
#pragma mark 上下滑动切换
-(void)qiehuanView:(UIPanGestureRecognizer *)cgr{
    //
    if (istuichu == 1) {
        return;
    }
    if (_speakTimer) {
        return;
    }
    CGPoint translation = [cgr translationInView: self.view];
    if (cgr.state == UIGestureRecognizerStateBegan )
    {
        direction = kCameraMoveDirectionNone;
    }else  if (cgr.state == UIGestureRecognizerStateChanged&& direction == kCameraMoveDirectionNone)
    {
        direction = [ self determineCameraDirectionIfNeeded:translation];
        if (direction == kCameraMoveDirectionUp) {
            _index--;
            
            if(_index<0){
                _index = 0;
                [SVProgressHUD showImage:nil status:@"没有了"];
                return;
            }
            
            if (_index<_ary.count) {
                [UIView animateWithDuration:0.25 animations:^{
                    _bgview.transform = CGAffineTransformMakeTranslation(0, -SCRE_HEIGHT);
                    _bgimg.transform = CGAffineTransformMakeTranslation(0, -SCRE_HEIGHT);
                }];
                _model = [_ary objectAtIndex:_index<0?0:_index];
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
                [dic setObject:_model.id forKey:@"id"];
                //            [SVProgressHUD showWithStatus:@"加载中..."];
                //            [[BusinessService shareInstance]kuaipai_detail:dic success:^(id result) {
                //                [SVProgressHUD dismiss];
                //                _model = result;
                //                [self initDta];
                //                [self initViewWill];
                //            } failure:^(id result) {
                //                [SVProgressHUD showErrorWithStatus:result];
                //            }];
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initdata:) name:@"initdataren" object:nil];
                [SVProgressHUD showWithStatus:@"加载中..."];
                [[BusinessService shareInstance]kuaipai_detail:dic success:^(id result) {
                    user = result;
                    [[BusinessService shareInstance]enterGroup:dic success:^(id result) {
                        [SVProgressHUD dismiss];
                        
                        models = result;
                        [timer invalidate];
                        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                                     bundle:[NSBundle mainBundle]];
//                        KPDViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"KPDViewController"];
                        [self addTheValue];
                        
//                        [self.navigationController pushViewController:searchResultDetailController animated:NO];
                        //                    [self presentViewController:searchResultDetailController animated:YES completion:nil];
                        return ;
                        
                    } failure:^(id result) {
                        _index++;
                        [SVProgressHUD showErrorWithStatus:result];
                        _bgview.transform = CGAffineTransformMakeTranslation(0, 0);
                        _bgimg.transform = CGAffineTransformMakeTranslation(0, 0);
                    }];
                } failure:^(id result) {
                    _index++;
                    [SVProgressHUD showErrorWithStatus:result];
                    _bgview.transform = CGAffineTransformMakeTranslation(0, 0);
                    _bgimg.transform = CGAffineTransformMakeTranslation(0, 0);
                }];
                
            }
        }
        if (direction == kCameraMoveDirectionDown) {
            _index++;
            
            if(_index<0){
                _index = 0;
            }
            if (_index>=_ary.count) {
                [SVProgressHUD showImage:nil status:@"没有了"];
                return;
            }
            
            if (_index<_ary.count) {
                [UIView animateWithDuration:0.25 animations:^{
                    _bgview.transform = CGAffineTransformMakeTranslation(0, SCRE_HEIGHT);
                    _bgimg.transform = CGAffineTransformMakeTranslation(0, SCRE_HEIGHT);
                }];
                _model = [_ary objectAtIndex:_index<0?0:_index];
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
                [dic setObject:_model.id forKey:@"id"];
                //            [SVProgressHUD showWithStatus:@"加载中..."];
                //            [[BusinessService shareInstance]kuaipai_detail:dic success:^(id result) {
                //                [SVProgressHUD dismiss];
                //                _model = result;
                //                [self initDta];
                //                [self initViewWill];
                //            } failure:^(id result) {
                //                [SVProgressHUD showErrorWithStatus:result];
                //            }];
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initdata:) name:@"initdataren" object:nil];
                [SVProgressHUD showWithStatus:@"加载中..."];
                [[BusinessService shareInstance]kuaipai_detail:dic success:^(id result) {
                    user = result;
                    [[BusinessService shareInstance]enterGroup:dic success:^(id result) {
                        [SVProgressHUD dismiss];
                        
                        models = result;
                        [timer invalidate];
                        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                                     bundle:[NSBundle mainBundle]];
//                        KPDViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"KPDViewController"];
                        [self addTheValue];
//                        [self.navigationController pushViewController:searchResultDetailController animated:NO];
                        //                    [self presentViewController:searchResultDetailController animated:YES completion:nil];
                        return ;
                        
                    } failure:^(id result) {
                        _index--;
                        [SVProgressHUD showErrorWithStatus:result];
                        _bgview.transform = CGAffineTransformMakeTranslation(0, 0);
                        _bgimg.transform = CGAffineTransformMakeTranslation(0, 0);
                        
                    }];
                } failure:^(id result) {
                    _index--;
                    [SVProgressHUD showErrorWithStatus:result];
                    _bgview.transform = CGAffineTransformMakeTranslation(0, 0);
                    _bgimg.transform = CGAffineTransformMakeTranslation(0, 0);
                }];
            }
        }
        if (direction == kCameraMoveDirectionRight) {//影藏
            //执行动画
            [UIView animateWithDuration:0.25 animations:^{
                _bgview.transform = CGAffineTransformMakeTranslation([_user.width intValue] > [_user.height intValue]?SCRE_WIDTH:SCRE_HEIGHT, 0);
            }];
            return;
        }
        if (direction == kCameraMoveDirectionLeft) {//显示
            [UIView animateWithDuration:0.25 animations:^{
                _bgview.transform = CGAffineTransformMakeTranslation(0, 0);
            }];
            return;
        }
        
    }
}

//上下切换后赋值，刷新界面
- (void)addTheValue {
    
    self.model = models;
    self.user = user;
    self.ary = _ary;
    self.notify = not;
    self.index = _index;
    [resultArray removeAllObjects];
    resultArray = nil;
    [imgdata removeAllObjects];
    imgdata = nil;
    [scview removeFromSuperview];
    scview = nil;
    [_lable removeFromSuperview];
    _lable = nil;
    [_namelabel removeFromSuperview];
    _namelabel = nil;
    [pinglunBtn removeFromSuperview];
    pinglunBtn = nil;
    [self viewWillAppear:NO];
    [self viewDidLoad];
    
}
#pragma  mark 发送
-(void)submitAction:(UIButton *)btn{
    
    
    if ([_hfText.text trim].length == 0) {
        [SVProgressHUD showErrorWithStatus:@"输入聊天内容"];
        return;
    }
    if (self.secondsCountDown != 5) {
        [QMUITips showInfo:[NSString stringWithFormat:@"%d秒后才能发言！",self.secondsCountDown] inView:self.view];
        return;
    }
    _inputView.hidden = YES;
    [self.view endEditing:YES];
    TCMessage* msg = [TCMessage newMessage];
    msg.typeChat = 200;
    msg.typeFile = 1;
    msg.from.name = [AppDelegate shareDelegate].user.nickname;
    msg.from.ID = [AppDelegate shareDelegate].user.uid;
    msg.from.head = [AppDelegate shareDelegate].user.headsmall;
    msg.to.ID = [NSString stringWithFormat:@"%@",_model.id];
    msg.to.name = _model.name;
    msg.to.head = _model.logosmall;
    
    msg.typeFile = 1;
    msg.state = forMessageStateHavent;
    msg.body = [[TCTextMessageBody alloc] init];
    msg.bodyText.content = _hfText.text;
    [msg.from setExtendValue:@"从哪儿来的?" forKey:@"from扩展"];
    [msg.to setExtendValue:@"快拍" forKey:@"快拍"];
    [msg.extDic addEntriesFromDictionary:[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"type",@"1", nil]];
    [msg.body setExtendValue:@"消息体的扩展" forKey:@"body扩展"];
    [msg setExtendValue:@"消息本身的扩展" forKey:@"msg扩展"];
    _hfText.text = nil;
    [resultArray addObject:msg];
    
    [_table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:resultArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    [self scrollToBottom];
    
    [[AppDelegate shareDelegate]sendMessage:msg];
    self.countTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateUi) userInfo:nil repeats:YES];
    
}
-(void)updateUi{
    self.secondsCountDown--;
    //    [_senderBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    if(self.secondsCountDown==0){
        [self.countTimer invalidate];
        [_senderBtn setTitle:@"发送" forState:UIControlStateNormal];
        _senderBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        self.secondsCountDown = 5;
        _senderBtn.userInteractionEnabled = YES;
        
    }else{
        _senderBtn.userInteractionEnabled = NO;
        [_senderBtn setTitle:[NSString stringWithFormat:@"%d秒",_secondsCountDown] forState:UIControlStateNormal];
        
    }
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([scrollView isKindOfClass:[UITextView class]]) {
        return;
    }
    
    _inputView.hidden = YES;
    [self.view endEditing:YES];
}
#pragma  mark ----------键-----盘------
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    [self registerForKeyboardNotifications];
    
    _inputView.hidden = NO;
    return YES;
}
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShownHes:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)keyboardWasShownHes:(NSNotification*)noti{
    //改变window的背景颜色
    self.view.window.backgroundColor = _table.backgroundColor;
    //  键盘退出的frame
    CGRect frame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];//UIKeyboardFrameEndUserInfoKey:键盘动画完成后的最终frame。
    
    //键盘实时y_
    CGFloat keyY = frame.origin.y;
    //    if (inputView) {
    //        keyY = SCRE_HEIGHT ;
    //        isUp = NO;
    //        [[NSNotificationCenter defaultCenter] removeObserver:self];
    //    }
    //    if(isUp){
    //        keyY = SCRE_HEIGHT ;
    //        isUp = NO;
    //        [[NSNotificationCenter defaultCenter] removeObserver:self];
    //    }
    //屏幕的高度
    CGFloat screenH = [[UIScreen mainScreen] bounds].size.height;
    
    //动画时间
    CGFloat keyDuration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    //执行动画
    [UIView animateWithDuration:keyDuration animations:^{
        _inputView.transform = CGAffineTransformMakeTranslation(0, keyY - screenH);

    }];
}

#pragma mark 在线人头像获取（5秒刷新一次）
-(void)inserhead{
    if (istuichu == 1) {
        return;
    }
    CGSize nameh = [ValidateHelper sizeOfText:[_user.userinfo objectForKey:@"nickname"] theFont:[UIFont systemFontOfSize:16]];
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:_model.id forKey:@"groupId"];
    [[BusinessService shareInstance]lastUserHeads:dic success:^(id result) {//获取快拍详细里面最新用户头像
        if (imgdata.count != 0) {
            [imgdata insertObject:[imgdata lastObject] atIndex:0];
            [imgdata removeLastObject];
        }
        if ([imgdata count] < [(NSMutableArray *)result count]) {
//            for (int i = imgdata.count; i<[(NSMutableArray *)result count] - 1; i++) { //xhw2018-2-2加
                for (int i = imgdata.count; i<[(NSMutableArray *)result count]; i++) {
                DTModel * model = result[i];
                [imgdata insertObject:model atIndex:0];
            }
        }
 
        //imgdata = result;
        if (istuichu == 1) {
            return;
        }
        //在线人头像
        if (!scview) {
            scview = [[UIScrollView alloc]initWithFrame:CGRectMake(nameh.width + 80, 0, SCRE_WIDTH - (nameh.width + 100), 60)];
            scview.showsVerticalScrollIndicator = NO;
            scview.showsHorizontalScrollIndicator = NO;
            //            scview.backgroundColor = [UIColor redColor];
            [_bgview addSubview:scview];
        }
        
        
        
        
        
        int h = 5;
        for (int  i = 0; i<imgdata.count; i++) {
            DTModel *mode = [imgdata objectAtIndex:i];
            UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(h, 40-30/2, 30, 30)];
            h = h + 30;
            [ValidateHelper setImage:mode.headsmall img:img istoux:YES];
            img.layer.cornerRadius = img.frame.size.width/2;
            img.clipsToBounds = YES;
            img.layer.borderColor = [UIColor whiteColor].CGColor;
            img.layer.borderWidth = 1;
            [scview addSubview:img];
            BaseButton *btn = [[BaseButton alloc]initWithFrame:img.frame];
            btn.name = mode.uid;
            [btn addTarget:self action:@selector(togeren:) forControlEvents:UIControlEventTouchUpInside];
            [scview addSubview:btn];
            
        }
        _lable.text = [NSString stringWithFormat:@"观众%d人",imgdata.count];
        scview.contentSize = CGSizeMake(h, 0);
        
    } failure:^(id result) {
    }];
}
#pragma mark 到个人
-(void)togeren:(BaseButton *)btn{  //点击头像到个人
    DTModel *model = [[DTModel alloc]init];
    model.uid = btn.name;
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    FriendDetailsMainVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"FriendDetailsMainVC"];
    searchResultDetailController.model = model;
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
    
}

#pragma mark 自己看到的（头部UI）
-(void)initViewzijikandao{
    _msgLogin.text = @"所有人员可听见你讲话";

    CGRect t = _titleview.frame;
    t.size.height = 60;
    _titleview.frame = t;
    _titleview.backgroundColor = [UIColor blackColor];
    _titleview.layer.opacity = 0.4;
    _titleview.hidden = YES;
    
    pinglunBtn = [[UIButton alloc]initWithFrame:CGRectMake(5, 35, 120, 30)];
    [pinglunBtn setTitle:@"评论及时通知我" forState:UIControlStateNormal];
    
    pinglunBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [pinglunBtn setImage:[UIImage imageNamed:@"fqhh_d"] forState:UIControlStateNormal];
    [pinglunBtn setImage:[UIImage imageNamed:@"fqhh_s"] forState:UIControlStateSelected];
    [pinglunBtn addTarget:self action:@selector(plactiontz:) forControlEvents:UIControlEventTouchUpInside];
    [_bgview addSubview:pinglunBtn];
    
    if([_model.getmsg intValue ]==1){
        pinglunBtn.selected = YES;
    }else{
        pinglunBtn.selected = NO;
    }
    [backbtn removeFromSuperview];
    if([_user.width intValue] > [_user.height intValue]){
//        if (!backbtn) {
             backbtn = [[UIButton alloc]initWithFrame:CGRectMake([AppDelegate shareDelegate].sheigt - 50, 0, 50, 60)];
             [[UIApplication sharedApplication].keyWindow addSubview:backbtn];
//        }
       
    }else{
//        if (!backbtn) {
            backbtn = [[UIButton alloc]initWithFrame:CGRectMake([AppDelegate shareDelegate].swhidth - 50, 0, 50, 60)];
             [[UIApplication sharedApplication].keyWindow addSubview:backbtn];
//        }
        
    }
//    [backbtn setTitle:@"X" forState:UIControlStateNormal];
    [backbtn setImage:[UIImage qmui_imageWithShape:QMUIImageShapeNavClose size:WH(15, 15) tintColor:UIColorWhite] forState:UIControlStateNormal];
    backbtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    
    [backbtn setTitleColor:colorBG forState:UIControlStateNormal];
   
    [backbtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [_btn1 setImage:[UIImage imageNamed:@"图标---回复"] forState:UIControlStateNormal];
    [_bnt2 setImage:[UIImage imageNamed:@"图标---交换窗口"] forState:UIControlStateNormal];
    [_btn3 setImage:[UIImage imageNamed:@"图标---评论关闭"] forState:UIControlStateNormal];
    [_btn3 setImage:[UIImage imageNamed:@"图标---评论开启"] forState:UIControlStateSelected];
    
    [_btn4 setImage:[UIImage imageNamed:@"图标---大屏"] forState:UIControlStateNormal];
    [_btn5 setImage:[UIImage imageNamed:@"图标---直播"] forState:UIControlStateNormal];
    [_btn5 setImage:[UIImage imageNamed:@"图标---退出直播"] forState:UIControlStateSelected];
    
    if (_model.meetingNum.length == 0) {
        _mic_btn.hidden = YES;
        _msgLogin.hidden = YES;
        _btn5.selected = NO;
    }else{
        _btn5.selected = YES;
        _mic_btn.hidden = NO;
        _msgLogin.hidden = NO;
    }
    if([_model.cancomment intValue ] == 1){
        _btn3.selected = NO;
    }else{
        _btn3.selected = YES;
    }
    
    CGRect g = _table.frame;
    g.origin.y = SCRE_HEIGHT/3;
    g.size.height = SCRE_HEIGHT/3;
    _table.frame = g;
}
#pragma mark 评论/分享
- (IBAction)btn1Action:(UIButton *)sender {
    
    _inputView.hidden = NO;
    _hfText.text = @"";
    [_hfText becomeFirstResponder];

}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex + 1 >= actionSheet.numberOfButtons ) {
        return;
    }
    
    
    NSInteger snsName = UMSocialPlatformType_QQ;
    if (buttonIndex == 0) {
        snsName = UMSocialPlatformType_Sina;
    }else if (buttonIndex == 1){
        snsName = UMSocialPlatformType_WechatSession;
    }else if (buttonIndex == 2){
        snsName = UMSocialPlatformType_WechatTimeLine;
    }else if (buttonIndex == 3){
        snsName = UMSocialPlatformType_Qzone;
    }else if (buttonIndex == 4){
        snsName = UMSocialPlatformType_QQ;
    }
    
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    UIImage *shareImage = [UIImage imageNamed:@"icon"];
    [[AppDelegate shareDelegate]refuser:_model.uid success:^(id as) {
        LoginResponseModel *loginRes = (LoginResponseModel *)as;
        NSString *url = [NSString stringWithFormat:@"%@?type=2&id=%@",sharepageurl,self.modelId];
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"一米社交" descr:[NSString stringWithFormat:@"一米社交的[%@]正在快拍直播",loginRes.nickname] thumImage:shareImage];
        //设置网页地址
        shareObject.webpageUrl = url;
        
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        
        [[UMSocialManager defaultManager] shareToPlatform:snsName messageObject:messageObject currentViewController:self completion:^(id result, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }
            else {
                if ([result isKindOfClass:[UMSocialShareResponse class]]) {
                    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"成功" message:@"分享成功" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
                    [alertView show];
                    NSMutableDictionary *dic= [[NSMutableDictionary alloc]init];
                    [dic setObject:@"1" forKey:@"type"];
                    [dic setObject:_model.id forKey:@"content"];
                    [dic setObject:@"1" forKey:@"isopen"];
                    
                    [dic setObject:@"0" forKey:@"isweibo"];
                    [dic setObject:@"0" forKey:@"isweixin"];
                    [dic setObject:@"0" forKey:@"isweixinquan"];
                    [dic setObject:@"0" forKey:@"isqqzone"];
                    [dic setObject:@"0" forKey:@"isqq"];
                    
                    if (buttonIndex == 0) {
                        [dic setObject:@"1" forKey:@"isweibo"];
                    }else if (buttonIndex == 1){
                        [dic setObject:@"1" forKey:@"isweixin"];
                    }else if (buttonIndex == 2){
                        [dic setObject:@"1" forKey:@"isweixinquan"];
                    }else if (buttonIndex == 3){
                        [dic setObject:@"1" forKey:@"isqqzone"];
                    }else if (buttonIndex == 4){
                        [dic setObject:@"1" forKey:@"isqq"];
                    }
                    [dic setObject:@"1" forKey:@"isopen"];
                    [[BusinessService shareInstance]sharerecord:dic success:^(id result) {
                        
                    } failure:^(id result) {
                        
                    }];
                }
                else {
                    UMSocialLogInfo(@"response data is %@",result);
                }
            }
        }];
    }];
    
    
    
}
/*
#pragma mark 分享回调
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的平台名
        //        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}
*/
#pragma mark 分享／打开闪光
- (IBAction)btn2action:(UIButton *)sender {
    //    if([_model.uid intValue] != [[AppDelegate shareDelegate].user.uid intValue]){
    UIActionSheet * editActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
    [editActionSheet addButtonWithTitle:@"微博"];
    [editActionSheet addButtonWithTitle:@"微信好友"];
    [editActionSheet addButtonWithTitle:@"朋友圈"];
    [editActionSheet addButtonWithTitle:@"QQ空间"];
    [editActionSheet addButtonWithTitle:@"QQ"];
    [editActionSheet addButtonWithTitle:@"取消"];
    editActionSheet.cancelButtonIndex = editActionSheet.numberOfButtons - 1;
    [editActionSheet showFromTabBar:self.tabBarController.tabBar];
    editActionSheet.delegate = self;
    //    }else{
    //        [SVProgressHUD showImage:nil status:@"闪光灯"];
    //    }
}
#pragma mark 举报/评论
- (IBAction)btn3Action:(UIButton *)sender {
    if([_model.uid intValue] != [[AppDelegate shareDelegate].user.uid intValue]){
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        ReportViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"ReportViewController"];
        searchResultDetailController.uid = _model.uid;
        searchResultDetailController.type = @"3";
        searchResultDetailController.content = _model.id;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    }else{
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:iscomm == 1 ? @"0" : @"1" forKey:@"cancomment"];
        [dic setObject:_model.getmsg forKey:@"getmsg"];
        [dic setObject:_model.id forKey:@"groupId"];
        [[BusinessService shareInstance]kuaipai_admin_setting:dic success:^(id result) {
            [SVProgressHUD showImage:nil status:@"设置成功"];
            _btn3.selected = !_btn3.selected;
        } failure:^(id result) {
            [SVProgressHUD showErrorWithStatus:result];
        }];
    }
}
#pragma mark 全屏
- (IBAction)btn4Action:(UIButton *)sender {
    //    _player.rate = 0;
    //    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
    //                                                                 bundle:[NSBundle mainBundle]];
    //    FullScreenViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"FullScreenViewController"];
    //    NSURL *url;
    //    if (![ValidateHelper isHttpHead:_user.video]) {
    //        url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",img_Url,_user.video]];
    //    }
    //    if (![ValidateHelper isHttpHead:_user.img]) {
    //        url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",img_Url,_user.img]];
    //        searchResultDetailController.isimg = YES;
    //    }
    //    searchResultDetailController.url = url;
    //    [self.navigationController pushViewController:searchResultDetailController animated:YES];
    //
    //执行动画
    isFullScreen = YES;
    [UIView animateWithDuration:0.25 animations:^{
        //右上角的两个”x"按钮重叠在一起，没有办法退出全屏(xhw11月15号改，注释下面的代码)
//        xbtn = [[UIButton alloc]initWithFrame:CGRectMake(SCRE_WIDTH - 60, 0, 50, 50)];
////        [xbtn setTitle:@"X" forState:UIControlStateNormal];
//        [xbtn setTitle:@"退出全屏" forState:UIControlStateNormal];
//        
//        [xbtn setTitleColor:colorBG forState:UIControlStateNormal];
//        [xbtn addTarget:self action:@selector(tuichuquanp:) forControlEvents:UIControlEventTouchUpInside];
//        [self.view addSubview:xbtn];
        _bgview.transform = CGAffineTransformMakeTranslation(0, SCRE_HEIGHT);
    }];
}
-(void)tuichuquanp:(UIButton *)btn{
    [UIView animateWithDuration:0.25 animations:^{
//        [xbtn removeFromSuperview];
        _bgview.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}
//xhw11月15号加
-(void)xhwtuichuquanp {
    [UIView animateWithDuration:0.25 animations:^{
        _bgview.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}
#pragma mark 赞/直播
- (IBAction)btn5Action:(UIButton *)sender {
    if([_model.uid intValue] != [[AppDelegate shareDelegate].user.uid intValue]){
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:_model.id forKey:@"groupId"];
        [[BusinessService shareInstance]kuaipai_zan:dic success:^(id result) {
            DMHeartFlyView* heart = [[DMHeartFlyView alloc]initWithFrame:CGRectMake(SCRE_WIDTH - 46, 0, 36, 36)];
            [_bgview addSubview:heart];
            CGPoint fountainSource = CGPointMake(SCRE_WIDTH - 46, self.view.bounds.size.height - 36/2.0 - 10);
            heart.center = fountainSource;
            [heart animateInView:self.view];
        } failure:^(id result) {
            [SVProgressHUD showErrorWithStatus:result];
        }];
    }else{
        if (sender.selected) {
            [SVProgressHUD showWithStatus:@"退出中..."];
            [[ECDevice sharedInstance].meetingManager deleteMultMeetingByMeetingType:ECMeetingType_MultiVoice andMeetingNumber: _model.meetingNum completion:^(ECError *error, NSString *meetingNumbers) {
                if (error.errorCode == ECErrorType_NoError)
                {
                    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
                    [dic setObject:meetingNumbers forKey:@"meetingNum"];
                    [dic setObject:_model.id forKey:@"groupId"];
                    [[BusinessService shareInstance]kuaipai_endMeeting:dic success:^(id result) {
                        [SVProgressHUD dismiss];
                        sender.selected = NO;
                        _mic_btn.hidden = YES;
                        _msgLogin.hidden = YES;
                    } failure:^(id result) {
                        
                    }];
                }
                else
                {   [SVProgressHUD dismiss];
                    NSString *msg = @"关闭直播失败，请稍后再试！";
                    [SVProgressHUD showErrorWithStatus:error.errorDescription.length==0?msg:error.errorDescription];
                }
            }];
        }else{
            [SVProgressHUD showWithStatus:@"开启中..."];
            ECCreateMeetingParams *params =[[ECCreateMeetingParams alloc]init];
            params.meetingType = ECMeetingType_MultiVoice;
            params.meetingName = _model.id;
            params.meetingPwd = @"yimisns";
            //        params.square= 1;
            params.autoClose = NO;
            params.autoJoin = YES;
            params.autoDelete = YES;
            params.voiceMod = 3;
            params.keywords = @"业务属性";
            
            [[ECDevice sharedInstance].meetingManager createMultMeetingByType:params completion:^(ECError *error, NSString *meetingNumbers) {
                //meetingNo 创建会议回调的会议号
                if (error.errorCode == ECErrorType_NoError)
                {
                    [[ECDevice sharedInstance].VoIPManager enableLoudsSpeaker:YES];
                    sender.selected = YES;
                    NSLog(@"会议创建成功，请讲话");
                    LoginResponseModel *mode = _model;
                    mode.meetingNum = meetingNumbers;
                    _model = mode;
                    meetingNumber = meetingNumbers;
                    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
                    [dic setObject:_model.id forKey:@"groupId"];
                    [dic setObject:meetingNumber forKey:@"meetingNum"];
                    [[BusinessService shareInstance]kuaipai_automeeting:dic success:^(id result) {
                        [SVProgressHUD dismiss];
                        _mic_btn.hidden = NO;
                        _msgLogin.hidden = NO;
                    } failure:^(id result) {
                    }];
                }
                else
                {
                    [SVProgressHUD dismiss];
                    NSString *msg = @"开启直播失败，请稍后再试！";
                    [SVProgressHUD showErrorWithStatus:error.errorDescription.length==0?msg:error.errorDescription];
                    
                    NSLog(@"会议创建失败，稍后重试");
                }
            }];
        }
    }
}
#pragma mark 直播说话开关/抢麦
- (IBAction)maiAction:(UIButton *)sender {
    if([_model.uid intValue] == [[AppDelegate shareDelegate].user.uid intValue]){
        
        isMute = !isMute;
        [[ECDevice sharedInstance].VoIPManager setMute:isMute];
        if (isMute) {
            _msgLogin.text = @"麦克风已关闭";
        }else{
            _msgLogin.text = @"所有人员可听见你讲话";
        }
    }
    
}
-(void)zanKuaipai:(NSNotification *)not{
    DMHeartFlyView* heart = [[DMHeartFlyView alloc]initWithFrame:CGRectMake(SCRE_WIDTH - 46, 0, 36, 36)];
    [_bgview addSubview:heart];
    CGPoint fountainSource = CGPointMake(SCRE_WIDTH - 46, self.view.bounds.size.height - 36/2.0 - 10);
    heart.center = fountainSource;
    [heart animateInView:self.view];
}
-(void)zhibojiesu:(NSNotification *)not{
    _mic_btn.hidden = YES;
    _msgLogin.hidden = YES;
}
-(void)zhibokaiqi:(NSNotification *)not{
    _mic_btn.hidden = NO;
    _msgLogin.hidden = NO;
}
#pragma 评论开关通知
-(void)iscomKuaipai:(NSNotification *)btn{
    TCNotify *not =  btn.object;
    NSMutableDictionary *dic = [JsonService jsonObjectWithString:not.content];
    iscomm = [[dic objectForKey:@"cancomment"] intValue];
    getMsg = [[dic objectForKey:@"cancoment"] intValue];
    if (iscomm == 1) {
        _btn1.userInteractionEnabled = YES;
        _btn1.selected = YES; //xhw2018-1-31改之前赋值的时候是搞调了的
        
        
    }else{
        _btn1.userInteractionEnabled = NO;
        _btn1.selected = NO;
    }
    
}
-(TCMessage *)newMessage{
    TCMessage* msg = [TCMessage newMessage];
    msg.typeChat = 200;
    msg.typeFile = 1;
    msg.state = forMessageStateHavent;
    msg.from.name = [AppDelegate shareDelegate].user.nickname;
    msg.from.ID = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
    msg.from.head = [AppDelegate shareDelegate].user.headsmall;
    msg.to.ID = [NSString stringWithFormat:@"%@",_model.id];
    msg.to.name = _model.name;
    msg.to.head = _model.logosmall;
    
    msg.typeFile = 1;
    return msg;
}


#pragma mark 语音

- (IBAction)btnTalkTouchBegin:(id)sender {
    NSLog(@"touchBegin");
    [self actionBarTalkStateChanged:TalkStateTalking];
}

- (IBAction)btnTalkTouchCancel:(id)sender {
    NSLog(@"touchCancel");
    [self actionBarTalkStateChanged:TalkStateNone];
}

- (IBAction)btnTalkTouchEnd:(id)sender {
    NSLog(@"touchEnd");
    [self actionBarTalkFinished];
}

- (IBAction)btnTalkDragInside:(id)sender {
    NSLog(@"GragInside");
    [self actionBarTalkStateChanged:TalkStateTalking];
}

- (IBAction)btnTalkDragOutside:(id)sender {
    NSLog(@"DragOutside");
    [self actionBarTalkStateChanged:TalkStateCanceling];
}

- (void)pressGesture: (UIGestureRecognizer *)sender {
    if ([sender state] == UIGestureRecognizerStateBegan) {
         NSLog(@"长按开始");
         [self actionBarTalkStateChanged:TalkStateTalking];
    }
    else if ([sender state] == UIGestureRecognizerStateEnded) {
        NSLog(@"长按结束");
        [self actionBarTalkStateChanged:TalkStateNone];
    }
    else {
        [self actionBarTalkStateChanged:TalkStateTalking];
        NSLog(@"长按中");
    }
    
}

-(IBAction)end:(UIButton *)btn{
    if(btn.tag == 726){
        isqiangmai = 0;
    }else{
        isqiangmai = 1;
    }
    [self actionBarTalkFinished];
}

- (void)actionBarTalkStateChanged:(TalkState)sts {
    //    [_player setVolume:0];
    if (sts == TalkStateTalking) {
        recordView.hidden = NO;
    } else if (sts == TalkStateCanceling) {
        recordView.hidden = NO;
    } else {
        recordView.hidden = YES;
    }
    recordView.state = sts;
}
- (void)actionBarTalkFinished {
    recordView.hidden = YES;
    [recordView recordEnd];
}
#pragma mark - TalkingRecordViewDelegate
- (void)recordView:(TalkingRecordView*)sender didFinish:(NSString*)path duration:(NSTimeInterval)du {
    TCDemoLog(@"record did finish %@, duration: %.0f", path, du);
    if (isqiangmai == 1) {
        if (du > 30) {
            [SVProgressHUD showErrorWithStatus:@"超过该麦时间"];
            return;
        }
    }
    if (du > 60.0) {
        [SVProgressHUD showErrorWithStatus:@"录音时间过长"];
        
    } else if (du > 2.0) {
        TCMessage* itemM = [self newMessage];
        
        itemM.body = [[TCVoiceMessageBody alloc] init];
        itemM.typeFile = forFileVoice;
        itemM.bodyVoice.voiceTime = du;
        itemM.bodyVoice.voiceUrl = path;
        [itemM.extDic addEntriesFromDictionary:[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"type",@"1", nil]];
        [resultArray addObject:itemM];
        
        [_table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:resultArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        [self scrollToBottom];
        [[AppDelegate shareDelegate]sendMessage:itemM];
        //        _player.volume = 1;
        
    } else {
        [SVProgressHUD showErrorWithStatus:@"录音时间过短"];
    }
}
//之前没有调用这个方法(xhw11月16号加)
#pragma mark 语音播放
-(void)bofang:(BaseButton *)btn{
    isbofgang = 1;
    [btn.imageView startAnimating];
    TCMessage *model = btn.model;
    [AudioMsgPlayer playWithURL:model.bodyVoice.voiceUrl delegate:self];
    
}
-(void)audioMsgPlayerDidFinishPlaying:(AudioMsgPlayer*)sender {
    //播放结束时执行的动作
    TCDemoLog(@"audioMsgPlayerDidFinishPlaying");
    isbofgang = 0;
}
//控麦
-(void)controlMic:(id)sender
{
    
    if(self.controlMicTimer) {
        [self.controlMicTimer invalidate];
        self.controlMicTimer = nil;
    } else {
        self.controlMicTimer = [NSTimer scheduledTimerWithTimeInterval:1. target:self selector:@selector(controlMic) userInfo:nil repeats:NO];
    }
}

#pragma  mark 抢麦
-(void)controlMic {
    controlMicBtnStatus = 1;
    __weak __typeof(self) weakSelf = self;
    NSString *meet;
    if (_model.meetingNum.length == 0) {
        meet = [AppDelegate shareDelegate].meetingNum;
    }else{
        meet = _model.meetingNum;
    }
    [[ECDevice sharedInstance].meetingManager controlMicInInterphoneMeeting:meet completion:^(ECError *error, NSString *memberVoip) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (error.errorCode == ECErrorType_NoError) {
            if (controlMicBtnStatus == 0) {
                controlMicBtnStatus = 2;
                [strongSelf releaseMic];
            } else {
                controlMicBtnStatus = 2;
                [SVProgressHUD showImage:nil status:@"抢麦成功，请讲话"];
                [strongSelf.speakTimer invalidate];
                strongSelf.speakTimer = [NSTimer scheduledTimerWithTimeInterval:1. target:strongSelf selector:@selector(speakTimeIntervalGrow) userInfo:nil repeats:YES];
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
            }
        } else {
            if (controlMicBtnStatus == 1) {
                [SVProgressHUD showImage:nil status:@"控麦失败，稍后重试"];
            }
            controlMicBtnStatus = 0;
        }
    }];
}
- (void)speakTimeIntervalGrow {
    speakTimeInterval ++ ;
    NSInteger mm = 0;
    NSInteger ss = 0;
    if (speakTimeInterval > 60) {
        mm = speakTimeInterval/60;
    }
    ss = speakTimeInterval % 60;
    _msgLogin.text = [NSString stringWithFormat:@"麦序剩余时间%0.2d:%0.2d", (int)mm, (int)ss];
}
- (void)releaseMic {
    if(self.controlMicTimer) {
        [self.controlMicTimer invalidate];
        self.controlMicTimer = nil;
    }
    if (controlMicBtnStatus == 2) {
        __weak __typeof(self) weakSelf = self;
        NSString *meet;
        if (_model.meetingNum.length == 0) {
            meet = [AppDelegate shareDelegate].meetingNum;
        }else{
            meet = _model.meetingNum;
        }
        [[ECDevice sharedInstance].meetingManager releaseMicInInterphoneMeeting:meet completion:^(ECError *error, NSString *memberVoip) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            if (error.errorCode == ECErrorType_NoError) {
                NSLog(@"放麦成功");
            } else {
                NSLog(@"放麦失败");
            }
            if (strongSelf.speakTimer) {
                speakTimeInterval = 0;
                _msgLogin.text = @"点击抢麦";
                [strongSelf.speakTimer invalidate];
                strongSelf.speakTimer  = nil;
            }
        }];
    }
    controlMicBtnStatus = 0;
}
//放麦
-(void)releaseMic:(id)sender
{
    [self releaseMic];
}





#pragma mark 评论通知
-(void)plactiontz:(UIButton *)btn{
    btn.selected = !btn.selected;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//    [dic setObject:[_model.getmsg intValue]==1?@"0":@"1" forKey:@"cancomment"];
//    [dic setObject:_model.cancomment forKey:@"getmsg"];
    [dic setObject:iscomm ==1?@"0":@"1" forKey:@"cancomment"];
    [dic setObject:getMsg==1?@"0":@"1" forKey:@"getmsg"]; //xhw2018-1-30加 开启getMsg和cancomment都是传1，关闭都是传0
    [dic setObject:_model.id forKey:@"groupId"];
    [[BusinessService shareInstance]kuaipai_admin_setting:dic success:^(id result) {
        [SVProgressHUD showImage:nil status:@"设置成功"];

        
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
}
#pragma mark 别人看到的（头部UI）
-(void)initViewbierenkandao{
    _msgLogin.text = @"点击抢麦";
    
    
    [_mic_btn addTarget:self action:@selector(releaseMic:) forControlEvents:UIControlEventTouchUpInside];
    [_mic_btn addTarget:self action:@selector(releaseMic:) forControlEvents:UIControlEventTouchUpOutside];
    [_mic_btn addTarget:self action:@selector(releaseMic:) forControlEvents:UIControlEventTouchCancel];
    [_mic_btn addTarget:self action:@selector(controlMic:) forControlEvents:UIControlEventTouchDown];
    
    
    
    CGRect t = _titleview.frame;
    t.size.height = 80;
    _titleview.frame = t;
    _titleview.backgroundColor = [UIColor blackColor];
    _titleview.layer.opacity = 0.4;
    _titleview.hidden = YES;
    
    
    UIImageView *head = [[UIImageView alloc]initWithFrame:CGRectMake(5, 40-35/2, 35, 35)];
    [ValidateHelper setImage:[_user.userinfo objectForKey:@"headsmall"] img:head istoux:YES];
    head.layer.cornerRadius = head.frame.size.width/2;
    head.clipsToBounds = YES;
    [_bgview addSubview:head];
    
    CGSize nameh = [ValidateHelper sizeOfText:[_user.userinfo objectForKey:@"nickname"] theFont:[UIFont systemFontOfSize:16]];
    if (!_namelabel) {
         _namelabel = [[UILabel alloc]initWithFrame:CGRectMake(45,head.frame.origin.y-5, nameh.width +10, 30)];
    }
   
    _namelabel.textColor = [UIColor whiteColor];
    _namelabel.text = [_user.userinfo objectForKey:@"nickname"];
    _namelabel.font = [UIFont systemFontOfSize:14];
    [_bgview addSubview:_namelabel];
    
    //    NSMutableDictionary *user =  _user.userinfo;
    UIButton *addbtn = [[UIButton alloc]initWithFrame:head.frame];
    addbtn.tag = 2016;
    //    if ([[user objectForKey:@"isfollow"] intValue]==0) {
    //        [addbtn setImage:[UIImage imageNamed:@"jgz"] forState:UIControlStateNormal];
    //    }else{
    //        [addbtn setImage:[UIImage imageNamed:@"kpxqzbgzqx"] forState:UIControlStateNormal];
    //    }
    [addbtn addTarget:self action:@selector(addguanzhu:) forControlEvents:UIControlEventTouchUpInside];
    [_bgview addSubview:addbtn];
    if([_user.width intValue] > [_user.height intValue]){
        if (!backbtn) {
            backbtn = [[UIButton alloc]initWithFrame:CGRectMake([AppDelegate shareDelegate].swhidth - 50, 0, 50, 60)];
            [[UIApplication sharedApplication].keyWindow addSubview:backbtn];
        }
    }else{
        if (!backbtn) {
            backbtn = [[UIButton alloc]initWithFrame:CGRectMake([AppDelegate shareDelegate].swhidth - 50, 0, 50, 60)];
            [[UIApplication sharedApplication].keyWindow addSubview:backbtn];
        }
        
    }
//    [backbtn setTitle:@"X" forState:UIControlStateNormal];
    [backbtn setImage:[UIImage qmui_imageWithShape:QMUIImageShapeNavClose size:WH(15, 15) tintColor:UIColorWhite] forState:UIControlStateNormal];
    backbtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    
    [backbtn setTitleColor:colorBG forState:UIControlStateNormal];
    
    [backbtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(inserhead) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    //    timer1 = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(setout) userInfo:nil repeats:YES];
    
    
    
    [_btn1 setImage:[UIImage imageNamed:@"图标---评论开启"] forState:UIControlStateNormal];
    [_btn1 setImage:[UIImage imageNamed:@"图标---评论关闭"] forState:UIControlStateSelected];
    
    if([_model.cancomment intValue ] == 1){
        _btn1.selected = NO;
    }else{
        _btn1.selected = YES;
        _btn1.userInteractionEnabled = NO;
    }
    
    
    
    CGRect g = _table.frame;
    g.origin.y = SCRE_HEIGHT/3;
    g.size.height = SCRE_HEIGHT/3;
    _table.frame = g;
    
}
-(void)setout{
    if (ot==0) {
        [timer1 invalidate];
    }
    ot--;
    
}
#pragma mark 添加主播关注
-(void)addguanzhu:(UIButton *)btn{
    NSMutableDictionary *user =  _user.userinfo;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    if ([[user objectForKey:@"isfollow"] intValue]==0) {
        [dic setObject:@"0" forKey:@"type"];
    }else{
        [dic setObject:@"1" forKey:@"type"];
    }
    [dic setObject:[user objectForKey:@"uid"] forKey:@"fid"];
    [[BusinessService shareInstance]follow:dic success:^(id result) {
        UIButton *btn = (UIButton *)[self.view viewWithTag:2016];
        if ([[user objectForKey:@"isfollow"] intValue]==0) {
            [SVProgressHUD showImage:nil status:@"关注成功"];
            LoginResponseModel *user = _user;
            NSMutableDictionary *d =  [[NSMutableDictionary alloc]init];
            [d setObject:[_user.userinfo objectForKey:@"headsmall"] forKey:@"headsmall"];
            [d setObject:[_user.userinfo objectForKey:@"nickname"] forKey:@"nickname"];
            [d setObject:[_user.userinfo objectForKey:@"uid"] forKey:@"uid"];
            [d setObject:@"1" forKey:@"isfollow"];
            user.userinfo = d;
            _user = user;
            [btn setImage:[UIImage imageNamed:@"kpxqzbgzqx"] forState:UIControlStateNormal];
        }else{
            LoginResponseModel *user = _user;
            NSMutableDictionary *d =  [[NSMutableDictionary alloc]init];
            [d setObject:[_user.userinfo objectForKey:@"headsmall"] forKey:@"headsmall"];
            [d setObject:[_user.userinfo objectForKey:@"nickname"] forKey:@"nickname"];
            [d setObject:[_user.userinfo objectForKey:@"uid"] forKey:@"uid"];
            [d setObject:@"0" forKey:@"isfollow"];
            user.userinfo = d;
            _user = user;
            [SVProgressHUD showImage:nil status:@"取消成功"];
            [btn setImage:[UIImage imageNamed:@"jgz"] forState:UIControlStateNormal];
        }
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
}
#pragma 人数变化通知
-(void)initnuber:(NSNotification *)not{
    TCNotify *notify;
    if (not==nil) {
        notify = _notify;
    }else{
        notify = not.object;
    }
    if (_lable) {
        NSMutableDictionary *dic = [JsonService jsonObjectWithString:notify.content];
        if(!dic){
            _lable.text = @"观众0人";
        }else{
            _lable.text = [NSString stringWithFormat:@"观众 %@人",[dic objectForKey:@"online"]];
        }
    }else{
        if([_model.uid intValue] == [[AppDelegate shareDelegate].user.uid intValue]){
            if (!_lable) {
                 _lable = [[UILabel alloc]initWithFrame:CGRectMake(5, 15, SCRE_WIDTH, 30)];
            }
           
            NSMutableDictionary *dic = [JsonService jsonObjectWithString:notify.content];
            if(!dic){
                _lable.text = [NSString stringWithFormat:@"%@人/目前在线人数%@人",@"0",@"0"];
            }else{
                _lable.text = [NSString stringWithFormat:@"%@人/目前在线人数%@人",[dic objectForKey:@"total"],[dic objectForKey:@"online"]];
            }
            _lable.font = [UIFont systemFontOfSize:15];
            _lable.textColor = [UIColor whiteColor];
            [_bgview addSubview:_lable];
            
        }else{
            if (!_lable) {
                _lable = [[UILabel alloc]initWithFrame:CGRectMake(45, 35, SCRE_WIDTH, 30)];
            }
            
            NSMutableDictionary *dic = [JsonService jsonObjectWithString:notify.content];
            if(!dic){
                _lable.text = @"观众0人";
            }else{
                _lable.text = [NSString stringWithFormat:@"观众 %@人",[dic objectForKey:@"online"]];
            }
            _lable.font = [UIFont systemFontOfSize:13];
            _lable.textColor = [UIColor whiteColor];
            [_bgview addSubview:_lable];
        }
    }
    
}
-(void)initGroupList:(NSNotification *)sender{
    TCMessage * msg = sender.object;
    if (msg.typeChat == 200 && [msg.withID isEqualToString:_model.id]) {
        if (!msg.isRead) {
            // 在聊天界面收到消息,标记为已读,更新数据库
            msg.isRead = YES;
            [[ThinkChat instance] hasReadSessionID:_model.id typeChat:200];
        }
        //        if (msg.isSendByMe) {
        resultArray = (NSMutableArray *)[[ThinkChat instance] getMessageListTimeLineWithID:_model.id typeChat:200 sinceRowID:0 maxRowID:0 count:3 page:0];
        [[ThinkChat instance]hasReadSessionID:_model.id typeChat:200];
        [_table reloadData];
        //        } else {
        //            BOOL shouldScroll = NO;
        //            if (_table.contentOffset.y + _table.frame.size.height >= _table.contentSize.height) {
        //                shouldScroll = YES;
        //            }
        //             if (shouldScroll) {
        //                 [_table reloadData];
        //            }
        //        }
    }
}
- (void)scrollToBottom
{
    //    if(resultArray.count>0){
    //        [_table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:resultArray.count-1   inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    //    }
    [[NSNotificationCenter defaultCenter]  addObserver:self  selector:@selector(initData:) name:@"getMessage" object:nil];
    NSInteger section  = [self numberOfSectionsInTableView:_table] - 1;
    if (section >= 0) {
        NSInteger row = [self tableView:_table numberOfRowsInSection:section] -1;
        if (row >= 0) {
            NSIndexPath * indxPath= [NSIndexPath indexPathForRow:row inSection:section];
            [_table scrollToRowAtIndexPath:indxPath atScrollPosition:UITableViewScrollPositionBottom  animated:YES];
        }
    }
}


- (void)clearSession:(NSNotification*)sender {
    TCSession* itemS = sender.object;
    for (TCSession* tmpS in resultArray) {
        if (tmpS.typeChat == itemS.typeChat && [tmpS.ID isEqualToString:itemS.ID]) {
            [resultArray removeObject:tmpS];
            [_table reloadData];
            break;
        }
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return resultArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KPCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KPCell"];
    TCMessage *mesmodel = [resultArray objectAtIndex:indexPath.row];
    
    if (mesmodel.typeFile == forFileText) {
        cell.name.text = [NSString stringWithFormat:@"%@:",mesmodel.from.name];
        for (UIView *view in  [cell.content subviews]) {
            [view removeFromSuperview];
        }
        cell.name.textColor = UIColorFromRGB(0xf7b250);
        
        MLEmojiLabel * _emojiLabel = [MLEmojiLabel new];
        _emojiLabel.numberOfLines = 0;
        _emojiLabel.font = [UIFont systemFontOfSize:13.0f];
        _emojiLabel.backgroundColor = [UIColor clearColor];
        _emojiLabel.lineBreakMode = NSLineBreakByWordWrapping;
        _emojiLabel.textColor = [UIColor whiteColor];
        
//        _emojiLabel.textInsets = UIEdgeInsetsMake(10, 0, 0, 0);
        _emojiLabel.textInsets = UIEdgeInsetsMake(10, 10, 0, 10);//xhw2018-3-12改
        _emojiLabel.isNeedAtAndPoundSign = YES;
        _emojiLabel.disableEmoji = NO;
        _emojiLabel.disableThreeCommon = YES;
        
        _emojiLabel.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;
        _emojiLabel.customEmojiRegex = @"\\[[emoji_[0-9]{1,3}]+\\]";
        _emojiLabel.customEmojiPlistName = @"expressionImage_custom.plist";
        
        if(mesmodel.isSendByMe){
            _emojiLabel.textColor = [UIColor whiteColor];
        }else{
            _emojiLabel.textColor = UIColorFromRGB(0xfd4f74);
        }
        [_emojiLabel setText:mesmodel.bodyText.content];
        CGSize  h =  [ValidateHelper sizeOfText:mesmodel.bodyText.content theFont:[UIFont systemFontOfSize:14]];
        CGSize ns =  [ValidateHelper sizeOfText:mesmodel.from.name theFont:[UIFont systemFontOfSize:14]];
        
        
        CGRect g = _emojiLabel.frame;
        int eh;
        //        if (h.width > (SCRE_WIDTH - ns.width)) {
        //            eh = (SCRE_WIDTH - ns.width)-25;
        //        }else{
        //            eh = h.width;
        //        }
        eh = SCRE_WIDTH*0.7;
        g.size.height = ([_emojiLabel preferredSizeWithMaxWidth:eh].height);
        g.origin.y = 0;
        g.size.width = eh;
        g.origin.x = 0;
        _emojiLabel.frame = g;
        [cell.content addSubview:_emojiLabel];
        
        CGRect b = cell.bgview.frame;
        b.size.width = eh + ns.width+13;
        b.origin.x = 5;
        b.size.height = g.size.height;
        cell.bgview.frame = b;
        
        CGRect c = cell.content.frame;
        c.origin.x = ns.width+10;
        c.size.width = g.size.width;
        cell.content.frame = c;
        
        
        
        
        CGRect cl = cell.frame;
        cl.size.height = g.size.height+5;
        cell.frame = cl;
        
    }else{
        for (UIView *view in  [cell.content subviews]) {
            [view removeFromSuperview];
        }
        cell.name.text = [NSString stringWithFormat:@"%@:",mesmodel.from.name];
        cell.name.textColor = UIColorFromRGB(0xf7b250);
        CGSize  h =  [ValidateHelper sizeOfText:mesmodel.from.name theFont:[UIFont systemFontOfSize:14]];
        TCVoiceMessageBody *body = (TCVoiceMessageBody *)mesmodel.body;
        
        BaseButton *button = [[BaseButton alloc]initWithFrame:CGRectMake(h.width + 5, 35/2-35/2, 50, 35)];
        button.model = mesmodel;
        [button setImage:[UIImage imageNamed:@"kpyy"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(bofang:) forControlEvents:UIControlEventTouchUpInside];
        [cell.bgview addSubview:button];
        
        CGRect na = cell.name.frame;
        na.size.height = 35;
        cell.name.frame = na;
        
        CGRect b = cell.bgview.frame;
        b.size.width = 50 + h.width;
        b.origin.x = 5;
        b.size.height = 35;
        cell.bgview.frame = b;
        
        CGRect cl = cell.frame;
        cl.size.height = 35;
        cell.frame = cl;
    }
    cell.selectionStyle = UITableViewCellAccessoryNone;
    //    cell.bgview.backgroundColor = [UIColor whiteColor];
    cell.bgview.layer.cornerRadius = 10;
    cell.bgview.clipsToBounds = YES;
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (istablescoolr != 1) {
        if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
            [_table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:resultArray.count-1   inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            istablescoolr = 1;
        }
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TCMessage *mesmodel = [resultArray objectAtIndex:indexPath.row];
    if ([mesmodel.from.ID intValue ]!=[[AppDelegate shareDelegate].user.uid intValue]) {
        [[AppDelegate shareDelegate]refuser:mesmodel.from.ID success:^(id as) {
            alert = [[UIAlertViews alloc] initWithFrame:CGRectMake(30, SCRE_HEIGHT, SCRE_WIDTH-60, 180)];
            alert.deleagte = self;
            [alert up];
            [alert bingd:mesmodel.from.head content:mesmodel.bodyText.content uid:mesmodel.from.ID mode:as];
            [[[[UIApplication sharedApplication] windows] firstObject] addSubview:alert];
        }];
    }
}
#pragma mark 点击名称弹出操作
-(void)didSelectBtn:(BaseButton *)btn{
    LoginResponseModel *user1 = btn.model;
    if (btn.tag == 100 ) { //踢出
        
        [[ThinkChat instance]deleteUser:user1.uid fromGroup:_model.id delegate:nil];
        [alert down];
        
        
        
    }else if (btn.tag == 101){//回复
        
        _hfText.text = [NSString stringWithFormat:@"@%@ ",user1.nickname];
        [alert down];
        [_hfText becomeFirstResponder];
        
        
    }else if (btn.tag == 102){//关注
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        if ([user1.isfriend intValue]==1 || [user1.isfriend intValue]==3) {
            [dic setObject:@"1" forKey:@"type"];
        }else{
            [dic setObject:@"0" forKey:@"type"];
        }
        [dic setObject:user1.uid forKey:@"fid"];
        [[BusinessService shareInstance]follow:dic success:^(id result) {
            if ([user1.isfriend intValue]==1 || [user1.isfriend intValue]==3) {
                [SVProgressHUD showImage:nil status:@"取消成功"];
            }else{
                [SVProgressHUD showImage:nil status:@"关注成功"];
            }
            [alert down];
        } failure:^(id result) {
            [SVProgressHUD showErrorWithStatus:result];
        }];
        
        
        
    }
    
    
}
#pragma mark 退出直播
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 1){
        [[ECDevice sharedInstance].meetingManager deleteMultMeetingByMeetingType:ECMeetingType_MultiVoice andMeetingNumber: _model.meetingNum completion:^(ECError *error, NSString *meetingNumbers) {
            if (error.errorCode == ECErrorType_NoError)
            {
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
                [dic setObject:meetingNumbers forKey:@"meetingNum"];
                [dic setObject:_model.id forKey:@"groupId"];
                [[BusinessService shareInstance]kuaipai_endMeeting:dic success:^(id result) {
                    UINavigationController *navigationVC = self.navigationController;
                    NSMutableArray *viewControllers = [[NSMutableArray alloc] init];
                    //    遍历导航控制器中的控制器
                    for (UIViewController *vc in navigationVC.viewControllers) {
                        [viewControllers addObject:vc];
                        if ([vc isKindOfClass:[SceneKPViewVC class]]) {
                            break;
                        }
                    }
                    //    把控制器重新添加到导航控制器
                    [navigationVC setViewControllers:viewControllers animated:YES];
                    
                } failure:^(id result) {
                    
                }];
            }
            else
            {
                //之前退出直播间失败没做处理，也就是说直播没有推出成功就推出不了当前页面(xhw11月14号加)
                [self back];
            }
        }];
    }
}
#pragma mark 返回方法
-(void)back{
    //xhw11月8号改
//    [self.navigationController popViewControllerAnimated:true];
//    return;
    UINavigationController *navigationVC = self.navigationController;
    NSMutableArray *viewControllers = [[NSMutableArray alloc] init];
    //    遍历导航控制器中的控制器
    for (UIViewController *vc in navigationVC.viewControllers) {
        [viewControllers addObject:vc];
//        if ([vc isKindOfClass:[SceneKPViewVC class]]) {
//            break;
//        }
        //xhw11月15号改
        if ([vc isKindOfClass:[KPDViewController class]]) {
            break;
        }
    }
    //    把控制器重新添加到导航控制器
    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",self.xhwZanCount],@"zancount", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"xhwInit" object:nil userInfo:dict];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"scollTop" object:nil userInfo:nil];
    [self.navigationController popToViewController:viewControllers[viewControllers.count-2] animated:YES];
//    if (viewControllers.count >= 2) {
//        [viewControllers removeObjectAtIndex:viewControllers.count-1];
//        [navigationVC setViewControllers:viewControllers animated:YES];
//    }
    
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
//    [navigationVC popViewControllerAnimated:YES];
    //之前上下滑动切换之后点击返回界面就只有一张白色的背景图，什么都操作不了了，相当于"死机"。(xhw10月31号改->1.注释了上面一句，2.重新打开了把控制器重新添加到导航控制器那一句代码)
//    [navigationVC popToViewController:viewControllers[viewControllers.count-1] animated:true];
//    if (viewControllers.count >= 3) {
//        [self.navigationController popToViewController:viewControllers[viewControllers.count-2] animated:NO];
//    }
//    else {
//        [self.navigationController popViewControllerAnimated:NO];
//    }
    
}
#pragma mark 返回事件
- (IBAction)backAction:(id)sender {
    //根据是否为全屏来执行不同的事情(xhw11月15号加)
    if (isFullScreen) {
        isFullScreen = NO;
        [self xhwtuichuquanp];
        return;
    }

    [timer invalidate];
    istuichu = 1;
    if (isbofgang == 1) {
        return;
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if([_model.uid intValue] != [[AppDelegate shareDelegate].user.uid intValue]){
        [[ECDevice sharedInstance].meetingManager exitMeeting];
        [self back];
        
    }else{
        if (!_mic_btn.hidden) {//直播状态下，先关闭直播在返回
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"当前正在直播，你确定返回退出直播？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }else{
            [self back];
            
        }
        
    }
}

- (void)tapAction:(UITapGestureRecognizer*)sender {
//    _inputView.hidden = YES;
//    [self.view endEditing:YES];
}



//- (void)dealloc {
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}


@end
